from __future__ import with_statement
import time
import sys
import simplejson as json
import httplib
import urllib
#import glob
import logging
#import logging.handlers

# parameters
API_KEY = '46251bd47d2a6017b46cc152ffdba0c1283ec097b3991e805145faddc0444eea'
API_URL = '/api/6001.xml'

run = True

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s %(levelname)s %(message)s',
                    filename='./send_to_gae.log')
logging.debug('Start send_to_gae')
while run:
    with open('/var/www/readings.json', 'r') as f:
        l = f.read().encode()
    try:
        readings = json.loads(l)
    except:
        logging.debug('json failure: '+"'"+l+"'")
        readings = {u'datetime': ''}

    #print readings

    params = urllib.urlencode({'content': l})
    conn = httplib.HTTPConnection('roqueislandmonitor.appspot.com')
    headers = {"Content-type": "application/x-www-form-urlencoded",
               "Accept": "text/plain"}
    conn.request('POST', '/reading', params, headers)
    resp = conn.getresponse()
    if resp.status != 200:
        #raise Exception(resp.reason)
        print resp.status
    resp.read()
    conn.close()

    time.sleep(60)
    # run = False
